package cn.com.hbhgkj.bussiness;

import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeanUtils;

import cn.com.hbhgkj.bussiness.exception.DuplicateRegistException;
import cn.com.hbhgkj.bussiness.exception.LoginFailedException;
import cn.com.hbhgkj.bussiness.exception.PwdNotMatchingException;
import cn.com.hbhgkj.bussiness.exception.UserNotValidException;
import cn.com.hbhgkj.common.DaoException;
import cn.com.hbhgkj.common.Pagination;
import cn.com.hbhgkj.common.ServiceException;
import cn.com.hbhgkj.config.Constants;
import cn.com.hbhgkj.dao.UserDao;
import cn.com.hbhgkj.pojo.User;

public class UserServiceImpl implements UserService {

	public List<User> findLikeCompanyName(String companyName,Pagination pagination) throws ServiceException {
		// TODO Auto-generated method stub
		try {
			return getUserDao().findLikeCompanyName(companyName,pagination);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	public void clearPassword(User loggedUser, User target)
			throws ServiceException {
		
		assertIsReviewer(loggedUser);
		try {
			User user = getUserDao().get(target.getId());
			user.setPassword(Constants.INIT_PASSWORD);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	// 用户信息修改
	public User updateUserInfo(User user) throws ServiceException {
		try {
			User queryUser = this.getUserDao().get(user.getId());
			assertPwdMatch(user, queryUser);
			BeanUtils.copyProperties(user, queryUser);
			return queryUser;
		} catch (DaoException e) {
			throw new ServiceException(e);
		}/*
		 * catch (IllegalAccessException e) { throw new ServiceException(e); }
		 * catch (InvocationTargetException e) { throw new ServiceException(e);
		 * } catch (NoSuchMethodException e) { throw new ServiceException(e); }
		 */
	}

	private void assertPwdMatch(User user, User queryUser)
			throws PwdNotMatchingException, ServiceException {
		if (!queryUser.getPassword().equals(user.getOrigPassword())) {
			throw new PwdNotMatchingException("原始密码不正确，修改失败!");
		}
	}

	// 用户注册
	public void regist(User user) throws ServiceException {
		try {
			if (isUserNameExist(user.getUserName())
					|| isCompanyNameExist(user.getCompanyName())) {
				throw new DuplicateRegistException("注册失败，存在相同用户名或单位名称/姓名！");
			}
			user.setUserType(UserType.APPLICANT.getValue());
			user.setStatus(ReviewCode.PENDING_REVIEW.getValue());
			user.setRegisterTime(new Date());
			userDao.save(user);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	// 获取需要审核的注册用户列表
	public List<User> getPendingReviews(Pagination pagination)
			throws ServiceException {
		try {
			return userDao.findByReviewCode(ReviewCode.PENDING_REVIEW,
					pagination);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	// 用户登录操作
	public void login(User user) throws ServiceException {

		User result = this.getUserByUserName(user.getUserName());
		assertLoginSuccess(user, result);
		try {
			PropertyUtils.copyProperties(user, result);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	private User getUserByUserName(String userName) throws ServiceException {
		try {
			List<User> users = getUserDao().findUsersByUserName(userName);

			if (users.size() > 0) {
				return users.get(0);
			}
			return null;

		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	private void assertLoginSuccess(User loginUser, User queryUser)
			throws ServiceException {
		if (queryUser == null)
			throw new LoginFailedException("登陆失败，不存在此用户信息！");

		if (!loginUser.getPassword().equals(queryUser.getPassword()))
			throw new LoginFailedException("登陆失败，用户的密码错误！");

		if (!ReviewCode.isPass(queryUser.getStatus())) {
			throw new LoginFailedException("登陆失败，用户未审核！");
		}

	}

	// 审核注册用户
	public void reviewRegisteration(User reviewer, User applicant)
			throws ServiceException {
		try {
			assertIsReviewer(reviewer);

			getUserDao().updateState(applicant);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	private boolean assertIsReviewer(User user) throws ServiceException {
		User result = getUserByUserName(user.getUserName());

		if (result == null || !UserType.isReviewer(user.getUserType()))
			throw new UserNotValidException("用户不存在或不合法，无法进行审核！");

		return true;
	}

	public void deleteUser(User user) throws ServiceException {
		try {
			this.getUserDao().delete(user);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	// 判断用户名是否存在
	public boolean isUserNameExist(String userName) throws ServiceException {
		try {
			List<User> users = this.getUserDao().findUsersByUserName(userName);

			if (users.size() > 0) {
				return true;
			}
			return false;

		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	// 判断单位或名字是否存在
	public boolean isCompanyNameExist(String companyName)
			throws ServiceException {
		try {
			List<User> users = this.getUserDao().findUsersByName(companyName);

			if (users.size() > 0) {
				return true;
			}
			return false;

		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	// 获取审核过的注册用户，包括审核成功和审核失败
	public List<User> getReviwed(Pagination pagination) throws ServiceException {
		try {
			return userDao.findByReviewCodes(new ReviewCode[] {
					ReviewCode.FAIL, ReviewCode.PASS }, pagination);
		} catch (DaoException e) {
			throw new ServiceException(e);
		}
	}

	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}
